<script setup lang="ts">
import {onMounted, ref} from "vue";
import { useSafetyManageHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";
import SirSelfCheckFormModal from "./sirSelfCheck-form-modal.vue";
import SirSelfCheckDetailModal from "./sirSelfCheck-detail-modal.vue"; // 引入详情弹窗组件
import SirSelfCheckBatchUpdateModal from "./sirSelfCheck-batch-update-modal.vue"; // 引入批量设置弹窗
import EditPen from "@iconify-icons/ep/edit-pen";
import Detail from "@iconify-icons/ep/view"; // 详情图标
import { SirSelfCheckBo } from "@/api/airport/dataManage/sirSelfCheck";
import AddFill from "@iconify-icons/ri/add-circle-line";
import {getDeptTree} from "@/api/system/dept";
import {getTagListApi, TagDTO} from "@/api/airport/dataManage/tagManage";
import {message} from "@/utils/message";
import SirSelfCheckImportModal from "./sirSelfCheck-import-modal.vue"; // 引入导入弹窗

defineOptions({
  name: "selfcheck"
});

const tableRef = ref();
const searchFormRef = ref();

const {
  searchFormParams,
  pageLoading,
  columns,
  dataList,
  pagination,
  timeRange,
  defaultSort,
  multipleSelection,
  onSearch,
  resetForm,
  onSortChanged,
  exportAllExcel,
  getSirSelfCheckList,
  handleDelete,
  handleBulkDelete,

} = useSafetyManageHook();

const opType = ref<"add" | "update">("add");
const modalVisible = ref(false);
const opRow = ref<SirSelfCheckBo>();
const detailVisible = ref(false); // 详情弹窗可见状态
const detailRow = ref<SirSelfCheckBo>(); // 详情弹窗数据
const deptTree = ref([]);
const tagOptions = ref<TagDTO[]>([]); // 标签下拉框数据

// 批量设置弹窗
const batchUpdateModalVisible = ref(false);
const batchUpdateType = ref<"tag" | "dept">("tag");
// 导入弹窗
const importModalVisible = ref(false);


function openDialog(type: "add" | "update", row?: SirSelfCheckBo) {
  opType.value = type;
  opRow.value = row;
  modalVisible.value = true;
}

// 打开导入弹窗
function openImportDialog() {
  importModalVisible.value = true;
}


function openDetail(row: SirSelfCheckBo) {
  detailRow.value = row;
  detailVisible.value = true;
}

// 打开批量设置弹窗
function openBatchUpdateDialog(type: "tag" | "dept") {
  if (multipleSelection.value.length === 0) {
    message("请至少选择一条数据", { type: "warning" });
    return;
  }
  batchUpdateType.value = type;
  batchUpdateModalVisible.value = true;
}

const {
  professionalOptions
} = useSafetyManageHook();


onMounted(async () => {
  try {
    const { data } = await getDeptTree();
    if (data) {
      // 转换数据格式
      const convertDeptTree = (nodes) => {
        return nodes.map(node => ({
          value: node.id,
          label: node.label,
          children: node.children ? convertDeptTree(node.children) : undefined
        }));
      };
      // 若 data 本身是数组，直接转换
      if (Array.isArray(data)) {
        deptTree.value = convertDeptTree(data);
      } else {
        // 若 data 不是数组，将其包裹成数组再转换
        deptTree.value = convertDeptTree([data]);
      }
    }
  } catch (error) {
    console.error('获取部门树数据失败:', error);
  }

  // 获取标签列表
  try {
    const { data } = await getTagListApi({
      pageSize: 300,
      pageNum: 1
    });
    if (data && data.rows) {
      tagOptions.value = data.rows;
    }
  } catch (error) {
    console.error('获取标签列表失败:', error);
  }

});

</script>

<template>
  <div class="main">
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="专业" prop="professional">
        <el-select
          v-model="searchFormParams.professional"
          placeholder="请选择专业"
          clearable
          class="!w-[200px]"
        >
          <el-option
            v-for="item in professionalOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="检查内容" prop="checkContent">
        <el-input
          v-model="searchFormParams.checkContent"
          placeholder="请输入检查内容"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>



      <el-form-item label="符合性判定标准" prop="complianceCriteria">
        <el-input
          v-model="searchFormParams.complianceCriteria"
          placeholder="请输入符合性判定标准"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item label="检查方式" prop="checkMethod">
        <el-input
          v-model="searchFormParams.checkMethod"
          placeholder="请输入检查方式"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item label="检查涉及部门" prop="checkDepartments">
        <el-input
          v-model="searchFormParams.checkDepartments"
          placeholder="请输入检查涉及部门"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>


      <el-form-item label="归属部门" prop="belongDept">
        <el-cascader
          v-model="searchFormParams.belongDept"
          :options="deptTree"
          :props="{
        value: 'value',
        label: 'label',
        emitPath: false,
        checkStrictly: true
      }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item label="标签" prop="tagId">
        <el-select
          v-model="searchFormParams.tagId"
          placeholder="请选择标签"
          clearable
          filterable
          class="!w-[200px]"
        >
          <el-option
            v-for="item in tagOptions"
            :key="item.tagId"
            :label="item.tagName"
            :value="item.tagId"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch(tableRef)"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="resetForm(searchFormRef, tableRef)"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="自查事项列表" :columns="columns" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog('add')"
        >
          新增自查事项
        </el-button>
        <el-button
          type="danger"
          :icon="useRenderIcon(Delete)"
          @click="handleBulkDelete(tableRef)"
        >
          批量删除
        </el-button>
        <el-button type="primary" @click="openImportDialog">
          导入部门数据
        </el-button>
        <el-button type="primary" @click="openBatchUpdateDialog('dept')">
          批量设置归属部门
        </el-button>
        <el-button type="primary" @click="openBatchUpdateDialog('tag')">
          批量设置标签
        </el-button>
        <el-button
          type="primary"
          @click="CommonUtils.exportExcel(columns, dataList, '自查事项列表')"
        >单页导出</el-button
        >
        <el-button type="primary" @click="exportAllExcel">全部导出</el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getSirSelfCheckList"
          @page-current-change="getSirSelfCheckList"
          @sort-change="onSortChanged"
          @selection-change="
            rows => (multipleSelection = rows.map(item => item.id))
          "
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('update', row)"
            >
              编辑
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="info"
              :size="size"
              :icon="useRenderIcon(Detail)"
              @click="openDetail(row)"
            >
              详情
            </el-button>
            <el-popconfirm
              :title="`是否确认删除编号为${row.id}的自查事项`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="danger"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <sirSelfCheck-form-modal
      v-model="modalVisible"
      :type="opType"
      :row="opRow"
      @success="onSearch"
    />
    <sirSelfCheck-detail-modal
      v-model="detailVisible"
      :row="detailRow"
    />
    <sirSelfCheck-batch-update-modal
      v-model="batchUpdateModalVisible"
      :type="batchUpdateType"
      :ids="multipleSelection"
      :dept-tree="deptTree"
      :tag-options="tagOptions"
      @success="resetForm(searchFormRef, tableRef)"
    />
    <!-- 导入弹窗 -->
    <sirSelfCheck-import-modal
      v-model="importModalVisible"
      :dept-tree="deptTree"
      @success="resetForm(searchFormRef, tableRef)"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
